package com.anrongtec.zcpt.utils;

/**
 * 作者：liuhui on 2017/2/12 22:48
 * 邮箱：liu594545591@126.com
 * 描述：HttpUtil
 */

import com.anrongtec.zcpt.constant.ShuJuURL;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.AbsCallback;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 联网请求工具类
 * @author cxy
 *
 */
public class HttpUtil {

    private static final long CONN_TIMEOUT = 30*1000;
    private static final long READ_TIMEOUT = 60*1000;
    private static final long WRITE_TIMEOUT = 60*1000;

    /**
     * post json
     * @param <T>
     * @param json
     */
    public static <T> void post(String json, AbsCallback<T> callback){

        try {
            OkHttpUtils.getInstance().post(ShuJuURL.JieKou_URL())
                    .postJson(json)
                    .connTimeOut(CONN_TIMEOUT)
                    .readTimeOut(READ_TIMEOUT)
                    .writeTimeOut(WRITE_TIMEOUT)
                    //可以全局统一设置缓存模式,默认就是Default,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy0216/
//			            .cacheMode(CacheMode.DEFAULT)
                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
//			            .cacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                    //可以设置https的证书,以下几种方案根据需要自己设置,不需要不用设置
//                    .setCertificates()                                  //方法一：信任所有证书
//                    .setCertificates(getAssets().open("srca.cer"))      //方法二：也可以自己设置https证书
//                    .setCertificates(getAssets().open("aaaa.bks"), "123456", getAssets().open("srca.cer"))//方法三：传入bks证书,密码,和cer证书,支持双向加密
//                    .addCommonHeaders(headers)      //设置全局公共头
//                    .addCommonParams(params);       //设置全局公共参数
                    .execute(callback);

		/*	callback一共有以下 7 个回调,除onResponse必须实现以外,其余均可以按需实现,每个方法参数详细说明,请看下面第6点:
		    parseNetworkResponse():解析网络返回的数据回调
			onBefore():网络请求真正执行前回调
			onResponse():网络请求成功的回调
			onError():网络请求失败的回调
			onAfter():网络请求结束的回调,无论成功失败一定会执行
			upProgress():上传进度的回调
			downloadProgress():下载进度的回调
			*/


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传json字符串
     * @param adress_Http	地址
     * @param strJson	json字符串
     * @return
     */
    public static int postJson(String adress_Http, String strJson) {

        String returnLine = "";
        int code = 0;
        try {

            System.out.println("**************调用的接口地址为**************" + adress_Http);
            System.out.println("**************请求发送的数据为**************" + strJson);
            URL my_url = new URL(adress_Http);
            HttpURLConnection conn = (HttpURLConnection) my_url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setConnectTimeout(30 * 1000);
            conn.setReadTimeout(30 * 1000);
//		   connection.setInstanceFollowRedirects(true);
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Connection", "Keep-Alive");

            Map<String, List<String>> requestProperties = conn.getRequestProperties();

            DataOutputStream out = new DataOutputStream(conn
                    .getOutputStream());

            byte[] content = strJson.getBytes();

            out.write(content);
            out.flush();
            out.close(); // flush and close

            code = conn.getResponseCode();

            //读
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            //StringBuilder builder = new StringBuilder();

            String line = "";

            System.out.println("Contents of post request start");

            while ((line = reader.readLine()) != null) {
                returnLine += line;

                System.out.println(line);
            }

            System.out.println("Contents of post request ends");

            reader.close();
            conn.disconnect();
            System.out.println("========返回的结果的为========" + returnLine);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return code;

    }


}

